﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Transactions;

public partial class WebForm_Auth_Role : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            listRoleID.DataBind();
            gv.DataBind();
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        var db = new DB();

        using (TransactionScope scope = new TransactionScope())
        {
            db.ExecuteNonQuery(string.Format(@"INSERT Role (RoleID, {0}, SystemDefine, Virtual, Status)
                                    SELECT @RoleID, @RoleName, 'N', 'N', 'Y'", LocManager.Current.GetTextCol("Role", "RoleName"))
                , new DBParameter("RoleID", txtRoleID.Text), new DBParameter("RoleName", txtRoleName.Text));

            db.ExecuteNonQuery(@"INSERT RoleUserMap (EmpID, RoleID)
                                    SELECT @EmpID, @RoleID"
                , new DBParameter("EmpID", EmpManager.Current.EmpID), new DBParameter("RoleID", txtRoleID.Text));

            scope.Complete();
        }

        gv.DataBind();
    }

    protected void btnQuery_Click(object sender, EventArgs e)
    {
        gv.DataBind();
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        gv.DataBind();
    }

    protected void gv_ItemCommand(object sender, GridViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "MyDelete":
                var row = (e.CommandSource as Control).NamingContainer as GridViewRow;
                var db = new DB();

                using (TransactionScope scope = new TransactionScope())
                {
                    var dt = db.Execute(@"SELECT RoleID FROM RoleFuncMap WHERE RoleID = @RoleID
                                        UNION SELECT RoleID FROM RoleOrgMap WHERE RoleID = @RoleID
                                        UNION SELECT RoleID FROM RoleUserMap WHERE RoleID = @RoleID"
                        , new DBParameter("RoleID", gv.DataKeys[row.RowIndex]["RoleID"]));

                    if (dt.Rows.Count > 0)
                    {
                        MyObj.ShowMessage(GetLocalResourceObject("btnDelete_HasAuthData").ToString());
                        return;
                    }

                    db.ExecuteNonQuery("DELETE Role WHERE RoleID = @RoleID "
                        , new DBParameter("RoleID", gv.DataKeys[row.RowIndex]["RoleID"]));

                    scope.Complete();
                }

                gv.DataBind();

                break;

            default:
                break;
        }
    }
}